﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.Mvc;
using KhuyenMaiVang.Models;
using KhuyenMaiVang.Areas.Admin.Models;
using KhuyenMaiVang.Helpers;
using KhuyenMaiVang.DAL;
using System.Data;
using System.Data.Entity;

namespace KhuyenMaiVang.Controllers
{
    public class AccountController : Controller
    {
        //
        // GET: /MemberAccount/
        private KhuyenMaiVangDataContext db = new KhuyenMaiVangDataContext();
        private DataProvider provider = new DataProvider();
        [Authorize(Roles = "Member")]
        public ActionResult Index()
        {
            return RedirectToAction("Profile");
        }
        public ActionResult LogOn()
        {
            if (User.IsInRole("Member"))
            {
                return RedirectToAction("Index");
            }
            else
            {
                return View();
            }
        }
        [HttpPost]
        public ActionResult LogOn(LoginUser model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.Email, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.Email, false);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Account");
                    }
                }
                else
                {
                    ModelState.AddModelError("","Sai email hoặc mật khẩu");
                }
            }
            return View(model);
        }
        public ActionResult RegisterMember()
        {
            return View();
        }
        [HttpPost]
        public ActionResult RegisterMember(ResUser user)
        {
            if (ModelState.IsValid)
            {
                if (user.Password == user.PasswordConfirm)
                {
                    if (!ProcessHelper.checkUsernameOrEmail(0, user.Username, user.Email))
                    {
                        User curUser = ProcessHelper.resUserToUser(user);

                        curUser.Password = ProcessHelper.md5AddSecret(user.Password);
                        curUser.Status = 1;
                        curUser.CreatedTime = DateTime.Now;
                        curUser.GroupID = 3;

                        db.Users.AddObject(curUser);
                        db.SaveChanges();
                        TempData["success"] = "Đã thêm thành viên:" + user.Username;
                        return RedirectToAction("Index", "Home");
                    }
                    else
                    {
                        ModelState.AddModelError("", "Đã có người sử dụng user hoặc email");
                        return View(user);
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Xác nhận mật khẩu không đúng");
                    return View(user);
                }
            }
            return View(user);
        }
        public ActionResult RegisterBusiness()
        {
            ViewBag.VoucherAdvertise = provider.DealsToDay();
            return View();
        }
        [HttpPost]
        public ActionResult RegisterBusiness(ResBusiness dataUser)
        {
            if (ModelState.IsValid)
            {
                ResUser user = dataUser.OrgUser;
                Business busUser = dataUser.OrgBusiness;
                if (user.Password == user.PasswordConfirm)
                {
                    if (!ProcessHelper.checkUsernameOrEmail(0, user.Username, user.Email))
                    {
                        User curUser = ProcessHelper.resUserToUser(user);

                        curUser.Password = ProcessHelper.md5AddSecret(user.Password);
                        curUser.Status = 1;
                        curUser.CreatedTime = DateTime.Now;
                        curUser.GroupID = 2;
                        db.Users.AddObject(curUser);
                        db.SaveChanges();
                        //Add Business Info
                        User loadUser = db.Users.Single(m=>m.Username == curUser.Username);
                        busUser.UserID = loadUser.ID;
                        db.Businesses.AddObject(busUser);
                        db.SaveChanges();
                        TempData["success"] = "Đã thêm doanh nghiệp:" + user.Username;
                        return RedirectToAction("Index", "Home");
                    }
                    else
                    {
                        ModelState.AddModelError("", "Đã có người sử dụng user hoặc email");
                        return View(dataUser);
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Xác nhận mật khẩu không đúng");
                    return View(dataUser);
                }
            }
           // ViewBag.VoucherAdvertise = 
            return View(dataUser);
        }
        [ChildActionOnly]
        public ActionResult UserControl()
        {
            if (User.Identity.IsAuthenticated)
            {
                string email = User.Identity.Name;
                User u = ProcessHelper.getUser(email);
                String dName = u.DisplayName;
                if (dName == "")
                {
                    dName = u.Username;
                }
                ViewBag.user = dName;
            }
            return PartialView();
        }

        [Authorize(Roles = "Member")]
        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Index");
        }
        [Authorize(Roles = "Member")]
        public ActionResult Profile()
        {
            ViewBag.TempDataSuccess = (String)TempData["success"];
            User curUser = ProcessHelper.getUser(User.Identity.Name);
            return View(curUser);
        }
        [Authorize(Roles = "Member")]
        public ActionResult UpdateInfo()
        {
            Request.ValidateInput();
            User curUser = ProcessHelper.getUser(User.Identity.Name);
            ResUser rUser = ProcessHelper.userToResUser(curUser);
            return View(rUser);
        }
        [Authorize(Roles = "Member")]
        [HttpPost]
        public ActionResult UpdateInfo(ResUser rUser)
        {
            if (ModelState.IsValid)
            {
                if (rUser.Password == rUser.PasswordConfirm)
                {
                    User orUser = ProcessHelper.getUser(User.Identity.Name);
                    User user = ProcessHelper.resUserToUser(rUser);
                    user.Password = ProcessHelper.md5AddSecret(rUser.Password);
                    user.Status = orUser.Status;
                    user.GroupID = orUser.GroupID;
                    user.CreatedTime = orUser.CreatedTime;
                    db.Users.Attach(user);
                    db.ObjectStateManager.ChangeObjectState(user, EntityState.Modified);
                    db.SaveChanges();
                    TempData["success"] = "Đã sửa thành viên:" + user.Username;
                    return RedirectToAction("Profile");
                }
                else
                {
                    ModelState.AddModelError("", "Xác nhận mật khẩu không đúng");
                }
            }
            return View(rUser);
        }
    }
}
